<?php

/**
 * Created by PhpStorm.
 * User: 杨胜飞
 * Date: 2017\8\26 0026
 * Time: 15:29
 */

namespace app\common\model;

use app\administrative\controller\Contractinfo;
use app\admin\controller\Base;
use think\db;
use app\common\model\Customer;
use app\common\model\Engineers;
use app\common\model\WorkOrderReturnModel;
use app\common\model\WorkOrderReturnVisitModel;
use think\Exception;
use think\Model;
use think\cache\driver\Redis;
use Wechat\WxAuth;
use app\common\model\Contract;

/**
 * Class WorkOrder
 * @package app\common\model
 *     工单表  模型
 */
class WorkOrderModel extends Model {

	protected $dateFormat = false;
	protected $name = 'work_order';

	/**
	 *    连表查询数量
	 * @param array $where
	 * @param array $join
	 * @return int|string
	 */
	public function getJoinCount($where = [], $join = []) {
		$result = $this->alias('a')
				->where($where)
				->join($join)
				->count();
		return $result;
	}

	// 分组查询
	public function getGroupAll($where, $join = [], $field = '*', $group = '') {
		$result = $this->alias('c')->where($where)
				->join($join)
				->group($group)
				->field($field)
				->select();
		return $result;
	}

	/**
	 * @param $data
	 * @return bool|false|int
	 *    添加数据
	 */
	public function add($data) {
		$result = $this->insertGetId($data);
		return $result;
	}

	/**
	 * @param $id
	 * @return $this|bool
	 *         根据主键ID 完成一次逻辑删除 或 恢复
	 */
	public function remove($id, $is_delete) {  // 工单id ，is_delete删除还是恢复
		// 根据主键ID 完成一次逻辑删除
		$result = $this->where('work_order_id', $id)->update(['is_delete' => $is_delete]);
		// 判断结果并返回
		if ($result !== 1) {
			return false;
		}
		return $result;
	}

	/**
	 * @param $where  ->  条件  ['key' => 'value']
	 * @param $data   ->  数据  ['key' => 'value','key' => 'value']
	 * @return $this|bool
	 *          根据条件 $where 完成一次数据修改
	 */
	public function edit($where, $data) {
		// 根据条件 $where 完成一次数据修改
		$result = $this->where($where)->update($data);
		// 判断数据 并返回
		if ($result !== 1) {
			return false;
		}
		return $result;
	}

	/**
	 * @param $data
	 * @return $this
	 *      ajax  异步修改 工单 处理状态
	 */
	public function editStatus($data, $u_id, $username, $company_name) {
		// 开启事务
		Db::startTrans();
		try {
			$where['work_order_id'] = $data['work_order_id'];
			$data['update_time'] = time();

			$work_order_status = config('work_order_status');

			$workData = $this->where($where)->find(); // 根据工单ID，获取工单数据
			//新工单审核
			if ($workData['work_order_status'] == 1) {
				$data['reception_time'] = time();
				$check_time = date('Y-m-d H:i:s', $data['reception_time']);

				// 发送消息
				// 模板内容
				$template_data = [
					'keyword1' => ['value' => '工单初次审核,工单号:' . $workData['order_number']],
					'keyword2' => ['value' => $work_order_status[$data['work_order_status']]],
					'keyword3' => ['value' => $check_time],
					'keyword4' => ['value' => $data['remarks']]
				];
				$template_id = config('wx_template')['check_result'];  // 模板ID
				//用户信息
				$user_model = new Customer();
				$userinfo = $user_model->one(array('user_id' => $workData['user_id']), 'telphone,openid');
				$template_tel = $userinfo['telphone'];  // 电话
				$template_content = '恭喜!您提交的工单已通过审核,我们将尽快为您安排工程人员!工单号:' . $workData['order_number'];
				if ($data['work_order_status'] == 2) {
					$template_content = '您好!该工单视为无效工单,如有疑问请联系平台客服,工单号:' . $workData['order_number'];   // 短信内容
				}
				if ($data['work_order_status'] == 3) {
					$template_content = '您好!经过客服与您沟通,该工单客服已处理,如有疑问请联系平台客服,工单号:' . $workData['order_number'];
				}
				if (!empty($data['remarks'])) {
					$template_content .= '!温馨提醒:' . $data['remarks'];
				}

				$this->sendNotifiy($userinfo['openid'], $template_data, $template_id, $template_tel, $template_content);
			}
			//工程人员退单审核
			if ($workData['work_order_status'] == 13) {
				//修改退单状态
				$return_model = new WorkOrderReturnModel();
				$return_map['work_order_id'] = $data['work_order_id'];
				$return_map['status'] = 1;
				$return_map['repair_id'] = $workData['repair_id'];
				$return_data['check_remarks'] = $data['remarks'];
				$return_data['check_time'] = time();
				$return_data['status'] = 3;
				if ($data['work_order_status'] == 4) {//审核通过
					$return_data['status'] = 2;
					//修改工单信息
					$data['repair_id'] = 0;
					$data['assignd_time'] = 0;
					$data['assigne_time'] = 0;
				}
				$return_model->edit($return_map, $return_data);
				//判断是否在redis抢单队列,若在,删除redis记录
				$redis = new Redis();
				$key = 'work_order_' . $data['work_order_id'];
				if ($redis->lSize($key) > 0) {
					$redis->rm($key);
				}
				$check_time = date('Y-m-d H:i:s', $return_data['check_time']);
				// 发送消息
				// 模板内容
				$template_content = '非常遗憾，您此次的退单未通过审核。,请继续完成此订单!工单号:' . $workData['order_number'];
				$remarks = '非常遗憾，您此次的审核未通过。点击此消息可查看审核详情。对审核过程或审核材料有任何疑问，都可进行咨询，我们一定会提供帮助！';
				if ($data['work_order_status'] == 4) {
					$remarks = '恭喜，您的审核已通过！赶快点击此消息进入小程序开始新的旅程吧！';
					$template_content = '恭喜，您提交的退单申请已通过审核,工单号:' . $workData['order_number'];   // 短信内容
				}
				if (!empty($data['remarks'])) {
					$template_content .= '!温馨提醒:' . $data['remarks'];
					$remarks .= '!温馨提醒:' . $data['remarks'];
				}
				$template_data = [
					'keyword1' => ['value' => '退单审核,工单号:' . $workData['order_number']],
					'keyword2' => ['value' => $work_order_status[$data['work_order_status']]],
					'keyword3' => ['value' => $check_time],
					'keyword4' => ['value' => $remarks]
				];
				$template_id = config('engineer_wx_template')['check_result'];  // 模板ID
				//用户信息
				$user_model = new Engineers();
				$userinfo = $user_model->getOne(array('engineers_id' => $workData['repair_id']), 'engineers_phone,openid');
				$template_tel = $userinfo['engineers_phone'];  // 电话
				$this->sendNotifiy($userinfo['openid'], $template_data, $template_id, $template_tel, $template_content);
			}
			$remarks = $data['remarks'];
			unset($data['remarks']);
			$workresult = $this->where($where)->update($data); //更新工单
			// 增加工单日志表记录
			$workLogData = [];
			$workLogData['work_order_id'] = $data['work_order_id'];			// 工单id
			$workLogData['operating_time'] = time();						   // 操作时间
			$workLogData['create_work_time'] = time();						 // 添加时间
			$workLogData['do_id'] = $u_id;									 // 操作人id
			$workLogData['operating_type'] = 3;								// 3为其他操作
			$workLogData['operating_status'] = $data['work_order_status'];	 // 操作状态
			$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】修改工单状态为：【' . $work_order_status[$data['work_order_status']] . '】';  // 备注
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			// 调用add方法增加工单日志数据
			$logresult = $workLogModel->add($workLogData);
			// 判断是否有备注，没有则不增加数据
			if (!empty($remarks)) {
				// 增加工单备注关联表
				$workRemarksData = [];
				$workRemarksData['u_id'] = $u_id;							   // 操作人id
				$workRemarksData['username'] = $username;					   // 操作人姓名
				$workRemarksData['operating_time'] = time();					// 操作时间
				$workRemarksData['work_order_id'] = $data['work_order_id'];	 // 工单id
				$workRemarksData['remarks'] = $remarks;				 // 备注信息
				// 实例化工单备注关联表
				$workRemarksModel = new WorkOrderRemarks();
				// 调用add方法增加工单备注关联表数据
				$remarkresult = $workRemarksModel->add($workRemarksData);
			}
			// 提交事务
			Db::commit();
			$rel = true;
		} catch (\Exception $e) {
			// 事务回滚
			Db::rollback();
			// dump($e->getMessage());
			$rel = false;
		}

		return $rel;
	}

	/**
	 * 消息通知--若有formId直接发送小程序模板消息,若无则发送服务号模板消息,若以上两者均发送失败,发送短信通知
	 * @param string $openid 小程序openid或者公众号openid
	 * @param string $weapp_template_id 小程序模板ID
	 * @param string $template_url 跳转小程序页面路径 pages/home/home?id=1
	 * @param array $weapp_template_data 小程序模板数据
	 * @param string $weapp_template_keyword 小程序放大关键字
	 * @param string $mp_template_id 公众号模板消息ID
	 * @param string $mp_template_data 公众号模板消息数据
	 * @param string $sms_tel 发送短信电话
	 * @param string $sms_content 发送短信内容
	 * @return type
	 */
	public function sendUserNotifiy($openid, $weapp_template_data, $weapp_template_id, $sms_tel, $sms_content, $template_url = '', $weapp_template_keyword = '', $mp_template_id = '', $mp_template_data = array()) {
		$mp_wx_config = config('wechat');
		$wx_config = config('wx');
		$mp_template_msg = array(
			'appid' => $mp_wx_config['appId'],
			'template_id' => $mp_template_id,
			'url' => 'https://www.youheone.com',
			'miniprogram' => array(
				"appid" => $wx_config['appId'],
				"pagepath" => $template_url
			),
			'data' => $mp_template_data
		);
		$weapp_form_id = $this->getFormId($openid);
		$WxAuth = new WxAuth($wx_config["appId"], $wx_config["appSecret"]);
		if (empty($weapp_form_id) || $weapp_form_id == false) {//不存在有效formId时发送公众号模板消息
			$res = false;
			if (!empty($mp_template_id) && !empty($mp_template_data)) {
				$res = $WxAuth->smallSendUniformMessage($openid, array(), $mp_template_msg, 'user');
			}
		} else {//存在formID 发送小程序模板消息
			$weapp_template_msg = array(
				'template_id' => $weapp_template_id,
				'page' => $template_url,
				'form_id' => $weapp_form_id,
				'data' => $weapp_template_data,
				'emphasis_keyword' => $weapp_template_keyword
			);
			$res = $WxAuth->smallSendUniformMessage($openid, $weapp_template_msg, $mp_template_msg, 'user');
		}
		//如果小程序模板消息和公众号模板消息都发送失败,发送短信
		if (!$res) {
			$res = $this->send_sms($sms_tel, $sms_content);
		}
		return $res;
	}

	/**
	 * @desc   发送模板消息
	 * @param
	 * @date   2018-08-04
	 * @author lcx
	 * @return [type]     [description]
	 */
	public function sendNotifiy($openid, $weapp_template_data, $weapp_template_id, $sms_tel, $sms_content, $template_url = '', $weapp_template_keyword = '', $mp_template_id = '', $mp_template_data = array()) {
		$mp_wx_config = config('wechat');
		$wx_config = config('engineer_wx');
		$mp_template_msg = array(
			'appid' => $mp_wx_config['appId'],
			'template_id' => $mp_template_id,
			'url' => 'https://www.youheone.com',
			'miniprogram' => array(
				"appid" => $wx_config['appId'],
				"pagepath" => $template_url
			),
			'data' => $mp_template_data
		);
		$weapp_form_id = $this->getFormId($openid);
		$WxAuth = new WxAuth($wx_config["appId"], $wx_config["appSecret"]);
		if (empty($weapp_form_id) || $weapp_form_id == false) {//不存在有效formId时发送公众号模板消息
			$res = false;
			if (!empty($mp_template_id) && !empty($mp_template_data)) {
				$res = $WxAuth->smallSendUniformMessage($openid, array(), $mp_template_msg, 'user');
			}
		} else {//存在formID 发送小程序模板消息
			$weapp_template_msg = array(
				'template_id' => $weapp_template_id,
				'page' => $template_url,
				'form_id' => $weapp_form_id,
				'data' => $weapp_template_data,
				'emphasis_keyword' => $weapp_template_keyword
			);
			$res = $WxAuth->smallSendUniformMessage($openid, $weapp_template_msg, $mp_template_msg, 'engineers');
		}
		//如果小程序模板消息和公众号模板消息都发送失败,发送短信
		if (!$res) {
			$res = $this->send_sms($sms_tel, $sms_content);
		}
		return $res;
	}

	/**
	 * @desc   发送短信验证码
	 * @param  无
	 * @date   2018-07-18
	 * @author lcx
	 * @param  [type]     $phone [description]
	 * @param  [type]     $yzm   [description]
	 * @return [type]            [description]
	 */
	public function send_sms($phone, $con) {
		//配置参数
		$sms_config = config('sms');
		$content = urlencode($con) . "。【" . $sms_config['content'] . "】";
		$gateway = "http://sms.bamikeji.com:8890/mtPort/mt/normal/send?uid=" . $sms_config['uid'] . "&passwd=" . md5($sms_config['passwd']) . "&phonelist=" . $phone . "&content=" . $content;
		$result = file_get_contents($gateway);
		$result = json_decode($result, true);
		return $result['code'];
	}

	/**
	 * @desc   保存获取
	 * @param
	 * @date   2018-08-04
	 * @author lcx
	 * @return [type]     [description]
	 */
	public function getFormId($openid) {
		$key = 'cloud_water:' . $openid;
		$redis = new Redis();
		$arr = $redis->rPop($key);
		if (empty($arr)) {
			return false;
		}
		$data = json_decode($arr, true);
		if ($data['expire_time'] > time()) {
			return $data['formId'];
		} else {
			$this->getFormId($openid);
		}
	}

	/**
	 * 添加备注信息
	 * @param $data
	 * @return $this
	 *   
	 */
	public function addRemarks($data, $u_id, $username, $company_name, $role = 0) {
		// 开启事务
		Db::startTrans();
		try {
			// 增加工单日志表记录
			$workLogData = [];
			$workLogData['work_order_id'] = $data['work_order_id'];			// 工单id
			$workLogData['operating_time'] = time();						   // 操作时间
			$workLogData['create_work_time'] = time();						 // 添加时间
			$workLogData['do_id'] = $u_id;									 // 操作人id
			$workLogData['operating_type'] = $role;								// 3为其他操作
			$workLogData['operating_status'] = '';	 // 操作状态
			$workLogData['is_to_user'] = 2;
			$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】添加工单备注';  // 备注
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			// 调用add方法增加工单日志数据
			$logresult = $workLogModel->add($workLogData);
			// 判断是否有备注，没有则不增加数据
			if (!empty($data['remarks'])) {
				// 增加工单备注关联表
				$workRemarksData = [];
				$workRemarksData['u_id'] = $u_id;							   // 操作人id
				$workRemarksData['username'] = $username;					   // 操作人姓名
				$workRemarksData['operating_time'] = time();					// 操作时间
				$workRemarksData['work_order_id'] = $data['work_order_id'];	 // 工单id
				$workRemarksData['remarks'] = $data['remarks'];				 // 备注信息
				// 实例化工单备注关联表
				$workRemarksModel = new WorkOrderRemarks();
				// 调用add方法增加工单备注关联表数据
				$remarkresult = $workRemarksModel->add($workRemarksData);
			}
			// 提交事务
			Db::commit();
			$rel = true;
		} catch (\Exception $e) {
			// 事务回滚
			Db::rollback();
			// dump($e->getMessage());
			$rel = false;
		}

		return $rel;
	}

	/**
	 * @desc   添加回访记录
	 * @param  无
	 * @date   2018-09-05
	 * @author lcx
	 */
	public function addVisit($data, $u_id, $username, $company_name, $role = 0) {
		Db::startTrans();
		try {
			$where['work_order_id'] = $data['work_order_id'];
			$edit_data['visit_status'] = $data['visit_status'];
			$this->where($where)->update($edit_data); //更新工单
			// 增加工单日志表记录
			$workLogData = [];
			$workLogData['work_order_id'] = $data['work_order_id'];			// 工单id
			$workLogData['operating_time'] = time();						   // 操作时间
			$workLogData['create_work_time'] = time();						 // 添加时间
			$workLogData['do_id'] = $u_id;									 // 操作人id
			$workLogData['operating_type'] = $role;								// 3为其他操作
			$workLogData['operating_status'] = '';	 // 操作状态
			$workLogData['is_to_user'] = 2;
			$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】将工单回访状态改成' . config('work_order_visit_status')[$data['visit_status']];  // 备注
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			// 调用add方法增加工单日志数据
			$logresult = $workLogModel->add($workLogData);
			//添加回访记录
			$visit_model = new WorkOrderReturnVisitModel();
			$visit_data['work_order_id'] = $data['work_order_id'];
			$visit_data['operator_client'] = $role;
			$visit_data['operator_uid'] = $u_id;
			$visit_data['operator_username'] = $username;
			$visit_data['remarks'] = $data['remarks'];
			$visit_data['status'] = $data['visit_status'];
			$visit_data['visit_time'] = time();
			$visit_model->add($visit_data);
			// 提交事务
			Db::commit();
			$rel = true;
		} catch (\Exception $e) {
			// 事务回滚
			Db::rollback();
			// dump($e->getMessage());
			$rel = false;
		}

		return $rel;
	}

	/**
	 * @desc   查询工单详情
	 * @param  无
	 * @date   2018-08-23
	 * @author lcx
	 * @param  [type]     $map   [description]
	 * @param  string     $filed [description]
	 * @param  array      $join  [description]
	 * @return [type]            [description]
	 */
	public function getOne($map, $filed = '*', $join = array()) {
		$data = $this->where($map)->join($join)->field($filed)->find();
		return $data;
	}

	/**
	 * @param $where
	 * @return int|string
	 *      查询工程人员已完成工单
	 */
	public function workCount($where) {
		$count = $this->where($where)->count();
		return $count;
	}

	/**
	 * @param $where   ->  条件   ['key' => 'value']
	 * @return array|bool|false|\PDOStatement|string|Model
	 *       根据条件 $where 查询单条数据
	 */
	public function getWEquipmentOne($where, $field = '*') {
		// 根据条件 $where 查询单条数据
		$userInfo = $this->where($where)
				->alias('wo')
				->join('rq_work_equipment we', 'wo.work_order_id = we.work_order_id')
				->field($field)
				->find();
		// 判断结果 并返回
		if ($userInfo == false) {
			return false;
		}
		return $userInfo;
	}

	/**
	 * @return bool|false|\PDOStatement|string|\think\Collection
	 *      查询 工单表 所有数据
	 */
	public function getList($where = '', $field = '*') {
		// 查询 工单表 所有 未被逻辑删除 数据
		$userInfo = $this->where(['is_delete' => 0])->where($where)->field($field)->select();
		// 判断结果 并返回
		if ($userInfo == false) {
			return false;
		}
		return $userInfo;
	}

	/**
	 * @param $id   ->  客户id
	 * @return false|\PDOStatement|string|\think\Collection
	 *        获取 工单 修改回显数据
	 */
	public function getEdit($id) {

		// 连表查询，获取工单管理列表页
		$data = Db::table('rq_work_order') //  工单表
				->alias('a')
				->join('rq_customer b', 'b.user_id = a.user_id') // 客户表 对应 工单表
				->join('rq_contract c', 'c.contract_id = a.contract_id') // 合同表 对应 工单表
				->join('rq_operation_info d', 'd.o_id = a.operation_id') // 区域合伙人表 对应 工单表
				->join('rq_engineers e', 'e.engineers_id = a.repair_id') // 工程人员表 对应 工单表
				->field('a.order_number,b.username,c.contract_no,d.company_name,b.area,
                               a.business_id,a.combo_money,a.work_order_status,a.order_time,
                               e.engineers_phone,c.moving_machine_number,a.work_order_id,
                               b.user_id,c.contract_id,d.o_id,e.engineers_id')// 工单号   户名     合同编号    区域合伙人   所属区域   工单类型  金额  处理状态   下单时间   工程部    移机次数 工单id
				->where('a.work_order_id', $id)
				->select();

		return $data;
	}

	/**
	 * @param $data
	 *       处理 工单信息修改
	 */
	public function getModify($data) {

		// 修改工单表 数据
		$workOrder = $this->allowField(true)->save($data, ['user_id' => $data['user_id']]);


		// 修改客户表 实例化客户表模型 Customer
		$customerModel = new Customer();
		// 生成条件
		$map = [];
		$map['user_id'] = $data['user_id'];
		// 修改数据
		$customerData['username'] = $data['username'];
		$customerData['area'] = $data['area'];
		// 调用 updateOne 方法 完成数据修改
		$customer = $customerModel->updateOne($map, $customerData);


		// 修改合同表 实例化合同表模型
		$contractModel = new Contract();
		// 生成条件
		$contractMap = [];
		$contractMap['user_id'] = $data['user_id'];
		// 修改数据  合同编号  移机次数
		$contractData['contract_no'] = $data['contract_no'];
		$contractData['moving_machine_number'] = $data['moving_machine_number'];
		// 调用 updateOne 方法 完成数据修改
		$contractModel->updateOne($contractMap, $contractData);


		// 修改工程人员 实例化
		$engineersModel = new Engineers();
		// 生成条件
		$engineersMap = [];
		$engineersMap['engineers_id'] = $data['repair_id'];
		// 修改数据  合同编号  移机次数
		$engineersData['engineers_name'] = $data['engineers_name'];
		// 调用 edit 方法 完成数据修改
		$engineersModel->edit($engineersMap, $engineersData);
	}

	/**
	 * @author ligang   修改参数$join可以为空，增加$whereOR,$whereTime参数
	 * @return bool|int|string
	 *      获取工单管理 数据的 总条数
	 *
	 */
	public function getCount($where, $dbName, $join = '', $whereOR = [], $whereTimeFiled = '', $whereTimeOp = '') {
		if (empty($join)) {
			if (empty($whereTimeFiled) && empty($whereTimeOp)) {
				$count = Db::table($dbName)		  // 主表
						->where($where)			 // 条件
						->whereOr($whereOR)
						->group('rq_work_order.work_order_id')
						->count();				  // 查询数据数量
			} else {
				$count = Db::table($dbName)		  // 主表
						->where($where)			 // 条件
						->whereOr($whereOR)
						->group('rq_work_order.work_order_id')
						->whereTime($whereTimeFiled, $whereTimeOp)
						->count();				  // 查询数据数量
			}
//            dump(Db::table($dbName)->getLastSql());
		} else {
			//  获取工单管理页面的总的条数
			$count = Db::table($dbName)		  // 主表
					->alias('a')				   // 主表别名
					->join($join)						// 需要关联的表
					->where($where)					  // 条件
					->group('a.work_order_id')
					->count();						   // 查询数据数量
		}
//        dump(Db::table($dbName)->getLastSql());
		// 返回结果
		return $count;
	}

	/*
	 * 计算工单金额
	 * @author ligang
	 * @param array     $where          条件
	 * @param string    $dbName         表名（含前缀）
	 * @param string    $field          统计的字段名
	 * @param array     $join           关联条件
	 * @param string    $whereTimeFiled 时间字段
	 * @param string    $whereTimeOp    时间规则
	 * @return  int
	 */

	public function countWorkOrderMoney($where, $dbName, $field, $join = [], $whereTimeFiled = '', $whereTimeOp = '') {
		if (empty($join)) {
			if (empty($whereTimeFiled) && empty($whereTimeOp)) {
				$result = Db::table($dbName)->where($where)->sum($field);
			} else {
				$result = Db::table($dbName)->where($where)->whereTime($whereTimeFiled, $whereTimeOp)->sum($field);
			}
		} else {
			if (empty($whereTimeFiled) && empty($whereTimeOp)) {
				$result = Db::table($dbName)->where($where)->join($join)->sum($field);
			} else {
				$result = Db::table($dbName)->where($where)->whereTime($whereTimeFiled, $whereTimeOp)->join($join)->sum($field);
			}
		}
//        dump(Db::table($dbName)->getLastSql());
		return $result;
	}

	/**
	 * @param int $nowPage
	 * @param string $limits
	 * @param int $id
	 * @param string $keywords
	 * @return false|\PDOStatement|string|\think\Collection
	 *         获取 所有工单列表页 数据  a.is_reminder asc,
	 */
	public function getAll($field = '*', $where = [], $nowPage = '', $limits = '', $dbName = '', $join = '', $order = 'a.order_time desc', $group = 'a.work_order_id') {

		// 连表查询，获取工单管理列表页
		$data = Db::table($dbName)		  // 主表
				->alias('a')		  // 主表别名
				->join($join)			   // 需要关联的表
				->field($field)			 // 需要查询的字段
				->where($where)			 // 条件
				->order($order)			 // 排序方式
				->group($group)
				->page($nowPage, $limits)	// 开始位置，多少数据
				->select();
//        echo Db::table($dbName)->getLastSql();exit;
		// 返回结果
		return $data;
	}

	/**
	 * @param int $id
	 * @return array
	 *        获取工单详情 数据
	 */
	public function getDetail($id = 0) { // 工单id
		// 获取工单详情  基本信息
		$basicData = Db::table('rq_work_order') // 工单表
				->alias('a')
				->join('rq_customer b', 'b.user_id = a.user_id', 'LEFT') // 客户表 对应 工单表
				->field('b.username,b.telphone,b.add_time,b.account_status,b.remark,b.birthday,b.province,b.city,b.user_address') // 基本信息中账号就是客户联系电话
				->where('a.work_order_id', $id) // 对应工单id号
				->select();

		// 获取工单详情  工单信息
		$workData = Db::table('rq_work_order')  // 工单表
				->alias('a')
				->join('rq_engineers b', 'b.engineers_id = a.repair_id', 'LEFT')			 // 工程人员表 对应 工单表
				->join('rq_contract j', 'j.contract_id = a.contract_id', 'LEFT')			 // 合同表 对应 工单表
				->join('rq_administrative_info h', 'h.a_id = a.administrative_id', 'LEFT')   // 行政中心表 对应 工单表
				->join('rq_operation_info r', 'r.o_id = a.operation_id', 'LEFT')			 // 区域合伙人表 对应 工单表
				->field('a.order_number,j.contract_no,a.business_id,r.company_name as y_name,h.company_name,
                                   a.work_order_status,b.engineers_name,b.engineers_phone,a.province,a.city,a.area,a.service_address,
                                   a.combo_money,a.move_address,a.contacts,a.contact_number,a.remarks,a.move_province,
                                   a.move_city,a.move_area,a.move_province_code,a.move_city_code,a.move_area_code,a.work_order_id')
				->where('a.work_order_id', $id)
				->select();
//        dump($workData);echo "<hr>";
		// 实例化工单设备关联表
		$workEquipmentModel = new WorkEquipment();
		if (!empty($workData)) {
			// 条件
			$workEquipmentWhere['work_order_id'] = $workData[0]['work_order_id'];
			// 连表操作
			$join = [
				['equipment_lists el', 'el.equipment_id = a.equipment_id', 'left'], // 工单设备表对应设备表
			];
			// 查询字段
			$field = 'el.equipment_id,el.device_no,a.work_order_id';
			// 获取设备编号
			$equipment_data = $workEquipmentModel->getJoinAll($workEquipmentWhere, $join, $field);
			if (empty($equipment_data)) {
				$equipmentNumbers = '';
			} else {
				$equipmentNumbers = $equipment_data;
			}
		}
//        dump(json_decode(json_encode($equipment_data),true));die();
		// 获取当前工单设备 当前工单的设备型号---当前工单的设备编号
		// 主表
//        $dbNmae = 'work_equipment';
//        // 连表
//        $join = [
//            ['equipment_lists el', 'el.equipment_id = w.equipment_id'],  // 设备表对应工单设备表
//            ['equipments e', 'e.equipments_id = el.equipments_id']   // 设备分类表对应设备表
//        ];
//        // 条件
//        $ewhere['w.work_order_id'] = $id;
//        // 查询字段
//        $field = 'el.equipment_id,el.device_no,e.model';
//        $equipmentNumbers = Db::name($dbNmae)->alias('w')->where($ewhere)->join($join)->field($field)->find();
		// 实例化工单配件关联表
		$workpartsModel = new WorkParts();
		$workpartswhere['work_order_id'] = $id;
		// 获取配件id
		$partsId = $workpartsModel->getAll($workpartswhere);
		// 实例化配件表
		$partsModel = new Parts();
		// 判断是否为空
		if (!empty($partsId)) {
			// 获取配件信息
			foreach ($partsId as $k => $v) {
				$partswhere['parts_id'] = $v['parts_id'];
				$partswhere['is_delete'] = 0;
				$parts_res = $partsModel->selectOne($partswhere);
				if ($parts_res) {
					$partsData[] = $parts_res;
				}
			}
			if (!empty($partsData)) {
				// 将配件信息跟配件数量合并
				foreach ($partsData as $k => $v) {
					$partsData[$k]['parts_number'] = $partsId[$k]['parts_number'];
				}
			}
		}
		// 如果没有就为空
		if (empty($partsData)) {
			$partsData = '';
		}

		// 获取工单详情  工单轨迹
		$userData = Db::name('work_order_log') // 工单日志表
				->field('create_work_time,operating_time,remarks')
				->where('work_order_id', $id)
				->order('operating_time desc')
				->limit(5)
				->select();

		// 拼接返回
		$arr = [
			'0' => $basicData,
			'1' => $workData,
			'2' => $userData,
			'3' => $equipmentNumbers,
			'4' => $partsData
		];

		return $arr;
	}

	/**
	 * @param string $id
	 * @param string $dbName
	 * @param string $field
	 * @param string $order
	 * @param int $limits
	 *          获取工单轨迹
	 */
	public function getLast($where = [], $page, $pageSize = 5, $dbName = 'work_order_log', $field = 'create_work_time,operating_time,remarks', $order = 'operating_time desc') {
// 获取工单详情  工单轨迹
		$userData = Db::name($dbName) // 工单日志表
				->field($field)
				->where($where)
				->page($page, $pageSize)
				->order($order)
				->select();
		return $userData;
	}

	/**
	 * @param $id
	 * @return false|\PDOStatement|string|\think\Collection
	 *         根据工程人员id  查询他名下所有已完成的工单  数量   工程人员板块
	 */
	public function getCompleted($id) { // 工程人员id
		// 拼接条件
		$where['repair_id'] = $id;
		$where['work_order_status'] = ['in', '11,12,15,16,17'];
		// 获取已完成的工单
		$count = $this->where($where)
				->count();
		// 返回
		return $count;
	}

	/**
	 * @param $id
	 * @return int|string
	 *       根据工程人员id  查询他名下所有未完成的工单数  数量   工程人员板块
	 */
	public function getUncompleted($id) { // 工程人员id
		// 拼接条件
		$where['repair_id'] = $id;
		$where['work_order_status'] = ['in', '8,9,10'];
		// 获取未完成的工单
		$count = $this->where($where)
				->count();
		// 返回
		return $count;
	}

	/**
	 * @param int $id
	 * @return false|\PDOStatement|string|\think\Collection
	 *          根据工程人员id  查询他名下所有已完成或待完成的工单数据    工程人员板块
	 */
	public function getCompleteds($id = 0, $nowPage = '', $limits = '', $searchObj = '', $startStatus = '', $endStatus = '') {
		// 判断用户有没有输开始日期
		if (empty($searchObj['startTime'])) {
			$startTime = '2005-01-01';
		} else {
			$startTime = $searchObj['startTime'];
		}

		// 判断用户有没有输结束日期
		if (empty($searchObj['endTime'])) {
			$endTime = date('Y-m-d', time());
		} else {
			$endTime = $searchObj['endTime'];
		}
		// 判断有没有输入工单号
		if (empty($searchObj['order_number'])) {
			$order_number = '';
		} else {
			$order_number = $searchObj['order_number'];
		}
		// 判断有没有输入用户名
		if (empty($searchObj['username'])) {
			$username = '';
		} else {
			$username = $searchObj['username'];
		}
		// 判断有没有输入合同编号
		if (empty($searchObj['contract_no'])) {
			$contract_no = '';
		} else {
			$contract_no = $searchObj['contract_no'];
		}
		// 判断有没有输入工单类型
		if (empty($searchObj['type'])) {
			$type = '';
		} else {
			$type = $searchObj['type'];
		}

		// 判断用户有没有输地区搜索  省 ，
		if (empty($searchObj['province'])) {
			$province = '';
		} else {
			$province = ['d.province_code' => $searchObj['province']];
		}
		// 判断用户有没有输地区搜索 市 ，
		if (empty($searchObj['city'])) {
			$city = '';
		} else {
			$city = ['d.city_code' => $searchObj['city']];
		}
		// 判断用户有没有输地区搜索 区，
		if (empty($searchObj['area'])) {
			$area = '';
		} else {
			$area = ['d.area_code' => $searchObj['area']];
		}
		// 将日期转换为时间戳，用于条件查询
		$startTime = strtotime($startTime);
		$endTime = strtotime($endTime);

		$data = Db::table('rq_engineers')  // 工程人员表
				->alias('a')
				->join('rq_work_order b', 'b.repair_id = a.engineers_id')  // 工单表 对应 工程人员表
				->join('rq_contract c', 'c.contract_id = b.contract_id')  // 合同表  对应 工单表
				->join('rq_customer d', 'd.user_id = b.user_id')		 //  客户表  对应 工单表
				->field('b.order_number,d.username,c.contract_no,d.area,b.business_id,d.user_address,b.combo_money,
                                   b.order_time,c.moving_machine_number,a.engineers_id,b.work_order_id')
				->where('work_order_status', ['>', $startStatus], ['<', $endStatus])
				->where('b.order_number', 'like', "%$order_number%")
				->where('d.username', 'like', "%$username%")
				->where('c.contract_no', 'like', "%$contract_no%")
				->where('b.business_id', 'like', "%$type%")
				->where($province)
				->where($city)
				->where($area)
				->where('b.order_time', ['>', $startTime], ['<', $endTime], 'and')
				->where('a.engineers_id', $id)
				->page($nowPage, $limits)
				->order('b.order_time desc')
				->select();
		return $data;
	}

	/**
	 * @param $id
	 * @return int|string
	 *         根据工程人员id ，获取他已完成的工单的总数   工程人员板块
	 */
	public function getCompletedCount($id, $searchObj = '', $startStatus = '', $endStatus = '') {
		// 判断用户有没有输开始日期
		if (empty($searchObj['startTime'])) {
			$startTime = '2005-01-01';
		} else {
			$startTime = $searchObj['startTime'];
		}

		// 判断用户有没有输结束日期
		if (empty($searchObj['endTime'])) {
			$endTime = date('Y-m-d', time());
		} else {
			$endTime = $searchObj['endTime'];
		}
		// 判断有没有输入工单号
		if (empty($searchObj['order_number'])) {
			$order_number = '';
		} else {
			$order_number = $searchObj['order_number'];
		}
		// 判断有没有输入用户名
		if (empty($searchObj['username'])) {
			$username = '';
		} else {
			$username = $searchObj['username'];
		}
		// 判断有没有输入合同编号
		if (empty($searchObj['contract_no'])) {
			$contract_no = '';
		} else {
			$contract_no = $searchObj['contract_no'];
		}
		// 判断有没有输入工单类型
		if (empty($searchObj['type'])) {
			$type = '';
		} else {
			$type = $searchObj['type'];
		}

		// 判断用户有没有输地区搜索  省 ，
		if (empty($searchObj['province'])) {
			$province = '';
		} else {
			$province = ['d.province_code' => $searchObj['province']];
		}
		// 判断用户有没有输地区搜索 市 ，
		if (empty($searchObj['city'])) {
			$city = '';
		} else {
			$city = ['d.city_code' => $searchObj['city']];
		}
		// 判断用户有没有输地区搜索 区，
		if (empty($searchObj['area'])) {
			$area = '';
		} else {
			$area = ['d.area_code' => $searchObj['area']];
		}

		// 将日期转换为时间戳，用于条件查询
		$startTime = strtotime($startTime);
		$endTime = strtotime($endTime);

		$data = Db::table('rq_engineers')  // 工程人员表
				->alias('a')
				->join('rq_work_order b', 'b.repair_id = a.engineers_id')  // 工单表 对应 工程人员表
				->join('rq_contract c', 'c.contract_id = b.contract_id')  // 合同表  对应 工单表
				->join('rq_customer d', 'd.user_id = b.user_id')		 //  客户表  对应 工单表
				->field('b.order_number,d.username,c.contract_no,d.area,b.business_id,d.user_address,b.combo_money,
                                           b.order_time,c.moving_machine_number,a.engineers_id')
				->where('work_order_status', ['>', $startStatus], ['<', $endStatus])
				->where('b.order_number', 'like', "%$order_number%")
				->where('d.username', 'like', "%$username%")
				->where('c.contract_no', 'like', "%$contract_no%")
				->where('b.business_id', 'like', "%$type%")
				->where($province)
				->where($city)
				->where($area)
				->where('b.order_time', ['>', $startTime], ['<', $endTime], 'and')
				->where('a.engineers_id', $id)
				->count();

		return $data;
	}

	public function getAllByWhere($map = [], $nowPage, $limits) {
		$data = Db::table('rq_engineers')  // 工程人员表
				->alias('a')
				->join('rq_work_order b', 'b.repair_id = a.engineers_id')  // 工单表 对应 工程人员表
				->join('rq_contract c', 'c.contract_id = b.contract_id', 'left')  // 合同表  对应 工单表
				->join('rq_customer d', 'd.user_id = b.user_id')		 //  客户表  对应 工单表
				->field('b.order_number,b.province,b.city,b.area,b.service_address,c.contract_no,d.area,b.business_id,d.user_address,b.combo_money,
                                   b.order_time,c.moving_machine_number,a.engineers_id,b.work_order_id,b.contact_number,b.contacts')
				->where($map)
				->page($nowPage, $limits)
				->order('b.order_time desc')
				->select();

		return $data;
	}

	/**
	 *    新增一条工单数据，获取他的id，同时增加一条工单日志数据,同时增加工单对应业务类型记录
	 * @param $data
	 * @param $username
	 * @param $u_id
	 * @param $company_name
	 * @param $equipment_id
	 * @param $workType
	 * @param $businessid
	 * @return bool
	 */
	public function insertId($data, $username, $u_id, $company_name, $equipment_id, $workType, $businessid) {
		// 获取工单业务类型
		$arr = [];
		foreach ($workType as $k => $v) {
			$arr[$v['business_type_id']] = $v['name'];
		}
		$workType = $arr;  // 工单类型
		// 获取添加业务类型名称 字符串
		$type = [];
		foreach ($businessid as $k => $v) {
			array_push($type, $workType[$v]);
		}
		$type = implode(',', $type);

		// 开启事务
		Db::startTrans();
		try {
			// 1-- 增加一条工单数据 获取他的id-----------------------------------
			$work_id = $this->allowField(true)->insertGetId($data);

			// 判断是否 有添加新装
			$isNew = false;
			foreach ($businessid as $k => $v) {
				if ($v == 3) {
					$isNew = true;
				}
			}
			// 没有新装的时候执行
			if (!$isNew) {
				// 2-- 工单设备关联表中插入一条数据-------------------------------
				$work_equipment = [
					'work_order_id' => $work_id,
					'equipment_id' => $equipment_id,
					'create_time' => time()
				];
				Db::name('work_equipment')->insertGetId($work_equipment);
			}

			// 3-- 调用add方法增加工单日志数据------------------------------------
			$workDataLog = [];
			$workDataLog['work_order_id'] = $work_id;	 // 工单id
			$workDataLog['create_work_time'] = time();	// 订单创建时间
			$workDataLog['operating_time'] = time();	  // 操作时间
			$workDataLog['operating_type'] = 0;		   // 操作类型  0为前台确认
			$workDataLog['operating_status'] = 1;		 // 操作状态为1  已处理
			$workDataLog['do_id'] = $u_id;				// 操作人id
			$workDataLog['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】添加工单类型【' . $type . '】';  // 备注信息
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			$resWorkLog = $workLogModel->add($workDataLog);

			// 4-- 添加工单类型关联表--------------------------------------------
			foreach ($businessid as $k => $v) {
				$work_order_business['work_order_id'] = $work_id;
				$work_order_business['business_id'] = $v;
				$work_order_business['money'] = $data['combo_money'];
				Db::name('work_order_business')->insertGetId($work_order_business);
			}

			// 5-- 增加工单备注关联表---------------------------------------------
			$workRemarksData = [];
			$workRemarksData['u_id'] = $u_id;															   // 操作人id
			$workRemarksData['username'] = $username;													   // 操作人姓名
			$workRemarksData['operating_time'] = time();													// 操作时间
			$workRemarksData['work_order_id'] = $work_id;												   // 工单id
			$workRemarksData['remarks'] = $data['remarks'];												 // 备注信息
			// 实例化工单备注关联表
			$workRemarksModel = new WorkOrderRemarks();
			// 调用add方法增加工单备注关联表数据
			$workRemarksModel->add($workRemarksData);

			// 提交事务
			Db::commit();
			$res = true;
		} catch (\Exception $e) {
			echo $e;
			// 事务回滚
			Db::rollback();
			$res = false;
		}
		// 返回结果
		return $res;
	}

	/**
	 * @param $where
	 * @param $editData
	 * @param $u_id
	 * @param $engineers_name
	 * @param $username
	 * @return bool
	 *          工单指派工程人员操作
	 */
	public function workassign($where, $editData, $u_id, $engineers_name, $username, $company_name) {
		// 开启事务
		Db::startTrans();
		try {
			// 根据工单ID获取工单号
			$workData = $this->where($where)->find();

			// 根据条件 $where 完成一次数据修改
			$result = $this->where($where)->update($editData);

			// 增加工单日志表记录
			$workLogData = [];
			$workLogData['work_order_id'] = $where['work_order_id'];	 // 工单id
			$workLogData['operating_time'] = time();					 // 操作时间
			$workLogData['create_work_time'] = time();				   // 添加时间
			$workLogData['do_id'] = $u_id;							   // 操作人id
			$workLogData['e_id'] = $editData['repair_id'];			   // 工程人员id
			$workLogData['operating_type'] = 1;						  // 1为工程部确认
			$workLogData['operating_status'] = 7;						// 指派
			$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】指派工单给工程人员：【' . $engineers_name . '】';  // 备注
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			// 调用add方法增加工单日志数据
			$workLogModel->add($workLogData);

			// 获取当前工单的信息
			$workwhere['work_order_id'] = $where['work_order_id'];
			$data = $this->getOne($workwhere);

			// 当指派工程人员是 修改 业务类型记录表
			$recordwhere['work_order_id'] = $where['work_order_id'];		// 工单id
			$record['repair_id'] = $editData['repair_id'];				  // 工程人员ID
			// 根据新增工单业务类型增加对应记录表数据
			// 表示增加续费工单
			if ($data['business_id'] == 1) {
				$renewModel = new RenewRecord();
				$recordData = $renewModel->modifyOne($recordwhere, $record);
			}
			// 表示换芯工单
			if ($data['business_id'] == 2) {
				$forcorerecordModel = new ForCoreRecord();
				$recordData = $forcorerecordModel->modifyOne($recordwhere, $record);
			}
			// 表示新装工单
			if ($data['business_id'] == 3) {
				$newrecordModel = new NewRecord();
				$recordData = $newrecordModel->edit($recordwhere, $record);
			}
			// 表示拆机工单
			if ($data['business_id'] == 4) {
				$disassembleModel = new DisassembleRecord();
				$recordData = $disassembleModel->modifyOne($recordwhere, $record);
			}
			// 表示移机工单
			if ($data['business_id'] == 5) {
				$shiftModel = new ShiftRecord();
				$recordData = $shiftModel->modifyOne($recordwhere, $record);
			}
			// 表示移机拆工单
			if ($data['business_id'] == 9) {
				$shiftModel = new ShiftRecord();
				$recordData = $shiftModel->modifyOne($recordwhere, $record);
			}
			// 表示移机装工单
			if ($data['business_id'] == 10) {
				$shiftModel = new ShiftRecord();
				$recordData = $shiftModel->modifyOne($recordwhere, $record);
			}
			// 表示维修工单
			if ($data['business_id'] == 6) {
				$repairModel = new RepairRecord();
				$recordData = $repairModel->edit($recordwhere, $record);
			}
			// 表示续费+维修工单
			if ($data['business_id'] == 7) {
				$renewrepairModel = new RenewRepairRecord();
				$recordData = $renewrepairModel->modifyOne($recordwhere, $record);
			}
			// 表示换芯+维修工单
			if ($data['business_id'] == 8) {
				$forcorerepairModel = new ForCoreRepairRecord();
				$recordData = $forcorerepairModel->modifyOne($recordwhere, $record);
			}

			// 提交事务
			Db::commit();
			$rel = true;
		} catch (\Exception $e) {
			// 事务回滚
			Db::rollback();
			$rel = false;
		}
		return $rel;
	}

	/**
	 * @param $where
	 * @param $workOrderData
	 * @param $username
	 * @param $u_id
	 * @return bool
	 *              工单确认+指派工程部操作
	 */
	public function departmentassign($where, $workOrderData, $username, $u_id, $company_name) {
		// 开启事务
		Db::startTrans();
		try {
			// 根据工单ID获取工单号
			$workData = $this->where($where)->find();

			// 根据条件 $where 完成一次数据修改
			$result = $this->where($where)->update($workOrderData);

			// 当为前台确认时
			if ($workOrderData['work_order_status'] == 3) {
				// 增加工单日志表记录
				$workLogData['work_order_id'] = $where['work_order_id'];		  // 工单id
				$workLogData['operating_time'] = time();						  // 操作时间
				$workLogData['create_work_time'] = time();						// 添加时间
				$workLogData['do_id'] = $u_id;									// 操作人id
				$workLogData['operating_type'] = 0;							   // 0为前台确认
				$workLogData['operating_status'] = 3;							 // 5为指派
				$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】已确认工单';  // 备注
				// 实例化工单日志表
				$workLogModel = new WorkOrderLog();
				// 调用add方法增加工单日志数据
				$workLogModel->add($workLogData);
			}
			// 当为指派工程部时
			if ($workOrderData['work_order_status'] == 5) {
				// 增加工单日志表记录
				$workLogData['work_order_id'] = $where['work_order_id'];		  // 工单id
				$workLogData['operating_time'] = time();						  // 操作时间
				$workLogData['create_work_time'] = time();						// 添加时间
				$workLogData['do_id'] = $u_id;									// 操作人id
				$workLogData['operating_type'] = 0;							   // 0为前台确认
				$workLogData['operating_status'] = 5;							 // 5为指派
				$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】指派工单给工程部';  // 备注
				// 实例化工单日志表
				$workLogModel = new WorkOrderLog();
				// 调用add方法增加工单日志数据
				$workLogModel->add($workLogData);
			}

			// 提交事务
			Db::commit();
			$rel = true;
		} catch (\Exception $e) {
			// 事务回滚
			Db::rollback();
			$rel = false;
		}
		return $rel;
	}

	/**
	 * @param $where
	 * @param $workOrderData
	 * @param $username
	 * @param $u_id
	 * @return bool
	 *            修改工单
	 */
	public function editWorkStatus($where, $workOrderData, $username, $u_id, $company_name, $remark = '') {
		// 开启事务
		Db::startTrans();
		try {
			// 根据工单ID获取工单号
			$workData = $this->where($where)->find();
			// 根据条件 $where 完成一次数据修改
			$result = $this->where($where)->update($workOrderData);
			// 增加工单日志表记录
			$workLogData['work_order_id'] = $where['work_order_id'];		  // 工单id
			$workLogData['operating_time'] = time();						  // 操作时间
			$workLogData['create_work_time'] = time();						// 添加时间
			$workLogData['do_id'] = $u_id;									// 操作人id
			$workLogData['operating_type'] = 0;							   // 0为前台确认
			$workLogData['operating_status'] = $workOrderData['work_order_status'];
			$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】' . $remark;  // 备注
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			// 调用add方法增加工单日志数据
			$workLogModel->add($workLogData);
			$rel = true;
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 事务回滚
			Db::rollback();
			$rel = false;
		}
		return $rel;
	}

	/**
	 * @param int $id
	 * @return array
	 *        获取工单详情 数据
	 */
	public function getDetails($id = 0) { // 工单id
		$data['obase'] = array();
		$data['yparts'] = array();
		// 获取工单详情  工单信息
		$workData = Db::table('rq_work_order')  // 工单表
				->alias('a')
				->join('rq_engineers b', 'b.engineers_id = a.repair_id') // 工程人员表 对应 工单表
				->join('rq_work_equipment c', 'c.work_order_id = a.work_order_id', 'left') // 设备工单关联表 对应 工单表
				->join('rq_contract_equipment ce', 'ce.id = c.contract_equipment_id', 'left') // 合同设备关连表 对应 设备工单关联表
				->join('rq_equipments d', 'd.equipments_id = ce.equipments_id', 'left') // 设备表 对应 设备工单关联表
				->join('rq_customer cu', 'a.user_id = cu.user_id') // 配件工单关联表 对应 工单表
				->join('rq_contract j', 'j.contract_id = a.contract_id', 'left') // 合同表 对应 工单表
				->join('rq_administrative_info h', 'h.a_id = a.administrative_id', 'left') // 行政中心表 对应 工单表
				->join('rq_operation_info r', 'r.o_id = a.operation_id', 'left') // 区域合伙人表 对应 工单表
				->field('a.work_order_id,a.service_address,a.order_number,j.contract_no,a.business_id,a.combo_money,r.company_name as y_name,h.company_name,
                                   a.work_order_status,b.engineers_name,b.engineers_phone,d.equipments_name,j.address,j.contract_id,
                                   j.for_core_cost,a.move_address,a.remarks,cu.telphone,cu.username,a.order_time,a.assigne_time')
				->where('a.work_order_id', $id)
				->find();
		if (!$workData) {
			return false;
		}
		//处理工单类型
		$workorder_type = config('workorder_type');
		$jobtype = $workorder_type[$workData['business_id']];
		$workData['jobtype'] = $jobtype;
		$data['obase'] = unsetnullArr($workData);
		$parts = Db::name('equipments_parts')->alias('ep')
				->join('rq_parts p', 'ep.parts_id = p.parts_id')
				->where(array('ep.contract_id' => $workData['contract_id'], 'ep.is_original' => 1))
				->field('ep.id,p.parts_id,p.parts_name,ep.parts_number')
				->select();
		$data['yparts'] = $parts;
		return $data;
	}

	/**
	 * @param $workOrderData
	 * @param $data
	 * @param $u_id
	 * @param $username
	 * @return bool
	 *        工单修改处理
	 */
	public function modify($workOrderData, $data, $u_id, $username, $company_name, $equipment_id) {

//        dump($data);die();
		// 开启事务
		Db::startTrans();
		try {
			// 判断是否 有添加新装
			$isNew = false;
			foreach ($data['businessid'] as $k => $v) {
				if ($v == 3) {
					$isNew = true;
				}
			}
			// 没有新装时执行
			if (!$isNew) {
				// 当业务类型不是新装时
				// 1-- 实例化工单设备关联表 完成一次修改---------------------------------------------------
				$wkEqModel = new WorkEquipment();
				$wkEqWhere['work_order_id'] = $data['work_order_id'];
				$wkEqData['equipment_id'] = $data['equipment_id'];
				$wkEqModel->edit($wkEqWhere, $wkEqData);
			} else {
				$contact_data['expect_exire_date'] = $workOrderData['expect_exire_date'];
				$contact_data['package_mode'] = $workOrderData['pac_mode'];
				$contact_data['package_value'] = $workOrderData['pac_num'];
				$contact_data['package_money'] = $workOrderData['pac_total_money'];
				$contact_data['package_cycle'] = $workOrderData['pac_cycle'];
				$contact_data['renew_money'] = $workOrderData['pac_renew_money'];
				$contact_data['contract_money'] = $workOrderData['pac_total_money'] * $workOrderData['equipment_num'];
				$contact_data['house_type'] = $workOrderData['house_type'];
				unset($workOrderData['pac_mode']);
				unset($workOrderData['pac_num']);
				unset($workOrderData['pac_total_money']);
				unset($workOrderData['pac_cycle']);
				unset($workOrderData['pac_renew_money']);
				unset($workOrderData['expect_exire_date']);
				unset($workOrderData['house_type']);
				$contract_model = new Contract();
				$contact_id = $contract_model->updateOne(['contract_id' => $workOrderData['contract_id']], $contact_data);
			}


			$workwhere['work_order_id'] = $data['work_order_id'];
			// 根据工单ID，获取工单号----------------------------------------------------------------------
			$workData = $this->where($workwhere)->find();
			// 2-- 根据条件 $where 完成一次工单数据修改---------------------------------------------------------

			$result = $this->where($workwhere)->update($workOrderData);

			// 3-- 删除之前的工单类型关联，然后新增-------------------------------------------------------------
			foreach ($data['_business'] as $k => $v) {
				// 实例化工单类型模型
				$work_business_mode = new WorkOrderBusinessModel();
				// 删除之前的
				$work_business_mode->delete(['work_order_id' => $data['work_order_id'], 'business_id' => $v]);
			}
			foreach ($data['businessid'] as $k => $v) {
				// 添加新的
				$work_business_mode->add(['work_order_id' => $data['work_order_id'], 'business_id' => $v, 'money' => $data['combo_money']]);
			}

			// 4-- 修改工单备注信息
			// 实例化工单备注关联表
			if (!empty($data['admin_remarks'])) {
				$workRemarksModel = new WorkOrderRemarks();
				$workRemarksModel->add(['work_order_id' => $data['work_order_id'], 'u_id' => $u_id, 'username' => $username, 'operating_time' => time(), 'remarks' => $data['admin_remarks']]);
			}
			if ($result) {
				// 5-- 增加工单日志表记录--------------------------------------------------------------------------
				$workLogData['work_order_id'] = $data['work_order_id'];			// 工单id
				$workLogData['operating_time'] = time();						   // 操作时间
				$workLogData['create_work_time'] = time();						 // 操作时间
				$workLogData['do_id'] = $u_id;									 // 操作人id
				$workLogData['operating_type'] = 3;								// 0为前台确认
				$workLogData['operating_status'] = $workData['work_order_status'];							 // 5为指派
				$workLogData['is_to_user'] = 2;
				$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】修改了工单内容,工单号为:【' . $workData['order_number'] . '】';  // 备注
				// 实例化工单日志表
				$workLogModel = new WorkOrderLog();
				// 调用add方法增加工单日志数据
				$logRel = $workLogModel->add($workLogData);
			}


			// 提交事务
			Db::commit();
			$rel = true;
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			echo $e->getMessage();
			$rel = false;
		}
		return $rel;
	}

	//   debug   新增一条工单数据，获取他的id，同时增加一条工单日志数据,同时增加对应业务类型记录
	public function insertIds($data, $username, $u_id, $contract_equipment_id, $company_name, $equipment_id) {
//        dump($equipment_id);die();
//        dump($data);die();
		// 开启事务
		Db::startTrans();
		try {
			// 增加一条工单数据 获取他的id
			$work_id = $this->allowField(true)->insertGetId($data);

			// 判断是否为添加新装
			if ($data['business_id'] == 3) {
				// 判断是否有合同编号
				if (!empty($data['contract_id'])) {
					// 实例化合同设备关联表,查询合同下面所有设备
					$ctEqModel = new Contract();
					$ctEqWhere['contract_id'] = $data['contract_id'];
					$ctEqData = $ctEqModel->getEquipmentAll($ctEqWhere);
					// 添加设备
					foreach ($ctEqData as $k => $v) {
						// 实例化工单设备关联表
						$wkEqModel = new WorkEquipment();
						$wkEqData['work_order_id'] = $work_id;
						$wkEqData['contract_equipment_id'] = $v['id'];
						$wkEqRel = $wkEqModel->add($wkEqData);
					}
				}
			} else {
				// 工单设备关联表中插入一条数据
				$work_equipment = [
					'work_order_id' => $work_id,
					'equipment_id' => $equipment_id,
					'create_time' => time()
				];
				Db::name('work_equipment')->insertGetId($work_equipment);
			}

			// 获取工单类型
			$workType = [1 => '续费', 2 => '换芯', 3 => '新装', 4 => '拆机', 5 => '移机', 6 => '维修', 7 => '续费+维修', 8 => '换芯+维修', 9 => '移机拆', 10 => '移机装'];

			// 声明一个空数组用来装工单日志表数据
			$workDataLog = [];
			$workDataLog['work_order_id'] = $work_id;	 // 工单id
			$workDataLog['create_work_time'] = time();	// 订单创建时间
			$workDataLog['operating_time'] = time();	  // 操作时间
			$workDataLog['operating_type'] = 0;		   // 操作类型  0为前台确认
			$workDataLog['operating_status'] = 1;		 // 操作状态为1  已处理
			$workDataLog['do_id'] = $u_id;				// 操作人id
			$workDataLog['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】添加工单类型【' . $workType[$data['business_id']] . '】';  // 备注信息
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			// 调用add方法增加工单日志数据
			$log = $workLogModel->add($workDataLog);

			// 业务类型记录表
			$record = [];
			$record['work_order_id'] = $work_id;				 // 工单id
			$record['user_id'] = $data['user_id'];			   // 客户id
			$record['repair_id'] = 0;							// 新增工单没有工程人员
			$record['contract_id'] = 0;	   // 合同ID
			$record['equipment_id'] = $contract_equipment_id;	// 合同设备关联id
			$record['remarks'] = '管理员【' . $username . '】【管理员ID为:' . $u_id . '】添加工单类型【' . $workType[$data['business_id']] . '】'; // 备注信息
			// 根据新增工单业务类型增加对应记录表数据
			// 表示增加续费工单
			if ($data['business_id'] == 1) {
				$record['renew_record_time'] = time();
				$renewModel = new RenewRecord();
				$recordData = $renewModel->insertOne($record);
			}
			// 表示增加换芯工单
			if ($data['business_id'] == 2) {
				$record['for_core_record_time'] = time();
				$forcorerecordModel = new ForCoreRecord();
				$recordData = $forcorerecordModel->insertOne($record);
			}
			// 表示增加新装工单
			if ($data['business_id'] == 3) {
				$record['new_record_time'] = time();
				$newrecordModel = new NewRecord();
				$recordData = $newrecordModel->add($record);
			}
			// 表示增加拆机工单
			if ($data['business_id'] == 4) {
				$record['disassemble_record_time'] = time();
				$disassembleModel = new DisassembleRecord();
				$recordData = $disassembleModel->add($record);
			}
			// 表示增移机工单
			if ($data['business_id'] == 5) {
				$record['shift_recordd_time'] = time();
				$shiftModel = new ShiftRecord();
				$recordData = $shiftModel->insertOne($record);
			}
			// 表示增移机拆工单
			if ($data['business_id'] == 9) {
				$record['shift_recordd_time'] = time();
				$shiftModel = new ShiftRecord();
				$recordData = $shiftModel->insertOne($record);
			}
			// 表示增移机装工单
			if ($data['business_id'] == 10) {
				$record['shift_recordd_time'] = time();
				$shiftModel = new ShiftRecord();
				$recordData = $shiftModel->insertOne($record);
			}
			// 表示维修工单
			if ($data['business_id'] == 6) {
				$record['repair_record_time'] = time();
				$repairModel = new RepairRecord();
				$recordData = $repairModel->add($record);
			}
			// 表示增续费+维修工单
			if ($data['business_id'] == 7) {
				$record['renew_repair_record_time'] = time();
				$renewrepairModel = new RenewRepairRecord();
				$recordData = $renewrepairModel->add($record);
			}
			// 表示增换芯+维修工单
			if ($data['business_id'] == 8) {
				$record['for_core_repair_record_time'] = time();
				$forcorerepairModel = new ForCoreRepairRecord();
				$recordData = $forcorerepairModel->insertOne($record);
			}
			if (!empty($data['admin_remarks'])) {
				// 增加工单备注关联表
				$workRemarksData = [];
				$workRemarksData['u_id'] = $u_id;															   // 操作人id
				$workRemarksData['username'] = $username;													   // 操作人姓名
				$workRemarksData['operating_time'] = time();													// 操作时间
				$workRemarksData['work_order_id'] = $work_id;												   // 工单id
				$workRemarksData['remarks'] = $data['admin_remarks'];												 // 备注信息
				// 实例化工单备注关联表
				$workRemarksModel = new WorkOrderRemarks();
				// 调用add方法增加工单备注关联表数据
				$remarksData = $workRemarksModel->add($workRemarksData);
			}


			// 提交事务
			Db::commit();
			$res = true;
		} catch (\Exception $e) {
			echo $e;
			// 事务回滚
			Db::rollback();
			$res = false;
		}
		// 返回结果
		return $res;
	}

	//   debug   工单修改
	public function modifys($workOrderData, $data, $u_id, $username, $company_name, $equipment_id) {
//        dump($workOrderData);echo "<hr>";
//        dump($data);die();
//        dump($equipment_id);die();
		// 开启事务
		Db::startTrans();
		try {

			// 判断是否新装工单修改
			if ($data['businessid'] == 3) {
				// 接受标识符并判断,1为已绑定合同,0为没有绑定合同
				if ($data['identifier'] == 1) {
//                    // 先删除，在添加
//                    // 实例化合同设备关联表,查询合同下面所有设备
//                    $ctEqModel = new Contract();
//                    $ctEqWhere['contract_id'] = $data['contract_id'];
//                    $ctEqData = $ctEqModel->getEquipmentAll($ctEqWhere);
//                    // 实例化工单设备关联表,删除所有设备
//                    $wkEqModel = new WorkEquipment();
//                    $wkEqWhere['work_order_id'] = $data['work_order_id'];
//                    $wkEqRel = Db::table('rq_work_equipment')->where($wkEqWhere)->delete();
					// 添加设备
//                    foreach ($ctEqData as $k => $v)
//                    {
//                        // 实例化工单设备关联表
//                        $wkEqModel = new WorkEquipment();
//                        $wkEqData['work_order_id'] = $data['work_order_id'];
//                        $wkEqData['contract_equipment_id'] = $v['id'];
//                        $wkEqRel = $wkEqModel->add($wkEqData);
//                    }
				} else {
//                    // 判断有没有选择合同
//                    if (!empty($data['contract_id'])) {
//                        // 实例化合同设备关联表
//                        $ctEqModel = new Contract();
//                        $ctEqWhere['contract_id'] = $data['contract_id'];
//                        $ctEqData = $ctEqModel->getEquipmentAll($ctEqWhere);
//                        foreach ($ctEqData as $k => $v)
//                        {
//                            // 实例化工单设备关联表
//                            $wkEqModel = new WorkEquipment();
//                            $wkEqData['work_order_id'] = $data['work_order_id'];
//                            $wkEqData['contract_equipment_id'] = $v['id'];
//                            $wkEqRel = $wkEqModel->add($wkEqData);
//                        }
//                    }
				}
			} else {
				// 当业务类型不是新装时
//                if (!empty($data['equipmentsname'])) {
//                    // 实例化工单设备关联表 完成一次修改
//                    $wkEqModel = new WorkEquipment();
//                    $wkEqWhere['work_order_id'] = $data['work_order_id'];
//                    $wkEqData['contract_equipment_id'] = $data['equipmentsname'];
//                    $wkEqModel->edit($wkEqWhere, $wkEqData);
//                }
			}

			$workwhere['work_order_id'] = $data['work_order_id'];

			// 根据工单ID，获取工单号
			$workData = $this->where($workwhere)->find();
			// 根据条件 $where 完成一次工单数据修改
			$result = $this->where($workwhere)->update($workOrderData);


//            // 当修改业务类型不为新装时，修改工单设备关联表
//            if (!$data['businessid'] == 3) {
//                // 实例化工单设备关联表 对它完成一次修改
//                $workEquipmentModel = new WorkEquipment();
//                $eqwhere['work_order_id'] = $data['work_order_id'];             // 工单ID
//                $eqData['contract_equipment_id'] = $data['equipmentsname'];     // 合同设备关联ID
//                $eqRel = $workEquipmentModel->edit($eqwhere,$eqData);
//            }
			// 修改工单设备表
			Db::name('work_equipment')->where($workwhere)->update(['equipment_id' => $equipment_id]);


			// 增加工单日志表记录
			$workLogData['work_order_id'] = $data['work_order_id'];			// 工单id
			$workLogData['operating_time'] = time();						   // 操作时间
			$workLogData['create_work_time'] = time();						   // 操作时间
			$workLogData['do_id'] = $u_id;									 // 操作人id
			$workLogData['operating_type'] = 3;								// 0为前台确认
			$workLogData['operating_status'] = 15;							 // 5为指派
			$workLogData['remarks'] = '【' . $company_name . '】管理员【' . $username . '】【管理员ID为:' . $u_id . '】修改了工单内容';  // 备注
			// 实例化工单日志表
			$workLogModel = new WorkOrderLog();
			// 调用add方法增加工单日志数据
			$logRel = $workLogModel->add($workLogData);

			// 提交事务
			Db::commit();
			$rel = true;
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$rel = false;
		}

		return $rel;
	}

	// 连表分组查询
	public function getJoinGroup($where, $join, $group, $field, $order) {
		$result = Db::name($this->name)->alias('a')
				->where($where)
				->join($join)
				->group($group)
				->field($field)
				->order($order)
				->select();
		return $result;
	}

	// 数量查询
	public function count($where = []) {
		$result = Db::name($this->name)
				->where($where)
				->count();
		return $result;
	}

	/**   YSF
	 *    获取工单详情
	 * @param array $where   查询条件
	 * @param array $join    连表操作
	 * @param string $field  查询字段
	 * @return null
	 */
	public function getWorkDetail($where = array(), $join = array(), $field = '*') {
		$result = Db::name($this->name)
				->join($join)
				->where($where)
				->field($field)
				->find();
		return $result;
	}

	// 连表列表查询
	public function getJoinAll($where = [], $join = [], $field = '*', $page = 1, $pageSize = 999, $order = '') {
		$result = $this->alias('a')
				->where($where)
				->join($join)
				->field($field)
				->page($page, $pageSize)
				->order($order)
				->select();
		return $result;
	}

	// 连表单条查询
	public function getJoinOne($where = [], $join = [], $field = '*') {
		$result = $this->alias('a')
				->where($where)
				->join($join)
				->field($field)
				->find();
		return $result;
	}

}
